/* eslint-disable @typescript-eslint/no-var-requires */
import React, { useState, useEffect, useRef } from 'react';
import { Button, Toast, SearchBar } from 'antd-mobile-v2';
import styles from './index.module.less';
import { getOutsideUserList } from '@/services/member';
import { PrintNum } from '@/utils';
// const IMAGE = require('@/assets/images/defaultAvator.png');
import Empty from '@/components/empty';
import AntdRefreshList from '@/components/antd-refresh-list';
import SwipeActionItem from '@/components/swipeAction-item';
import EmptyLoading from '@/components/empty/empty-loading';
import EmptyRefresh from '@/components/empty/empty-refresh';
import { useRefreshList } from '@/hooks/use-refresh-list';
import { Prompt } from 'react-router-dom';

type ParamsObj = {
  params: {
    page: number;
    limit: number;
    cardCode?: string;
    mobile?: string;
    openAccountName?: string;
    lastId: string,
    keyWord: string
  },
  lastArr: []
};

const height = document.documentElement.clientHeight - document.documentElement.clientWidth * (67 + 44) / 375;
const defaultPageSize = 10;

const Member: React.FC<any> = (props) => {

  const [pageSize, setPageSize] = useState(defaultPageSize);
  const [searchValue, setSearchValue] = useState<string>(''); // 输入框输入的值
  const [searchList, setSearchList] = useState<any[]>([]); // 搜索结果列表
  const [searchStatus, setSearchStatus] = useState<boolean>(false); // false展示搜索的列表 true展示全部人列表
  const [isError, setIsError] = useState(false);
  const { current } = useRef({ timer: null });

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    initSearchData: { keyWord: '', }, // 搜索关键字
    cacheRouteList: [
      '/member/create',
      '/member/detail',
    ],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      const reqParams = {
        limit: params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize,
        keyWord: params.keyWord,
        lastId: params.lastId,
      };
      setSearchValue(params.keyWord)
      try {
        const res = await getOutsideUserList(reqParams);
        const list = res.data?.rows || [];
        const surplusTotal = res.data?.total - list.length; // 加载完当前请求的数据还剩多少条数据
        setSurplusTotal(surplusTotal < 0 ? 0 : surplusTotal);
        setPageSize(params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize);
        setData(params?.lastId ? dataSource.concat(list) : list);
        setLastId(list[list.length - 1]?.id);
        setIsError(false);
      } catch (error) {
        setIsError(true);
      }
    }
  });

  const ChangMembers = (arr: []) => {
    if (searchStatus) {
      setDatasource(arr);
    } else {
      setDatasource(arr);
    }
  }

  const onAdd = () => {
    props.history.push('/member/create');
  };

  // 搜索列表
  const handleSearchFn = async function (val) {
    const searchVal = val.trim();
    setSearchValue(searchVal);
    if (current.timer) {
      clearTimeout(current.timer);
    }
    current.timer = setTimeout(async () => {
      setSearchStatus(true);
      handleSearch({ keyWord: val })
    }, 800);
  };

  const actionList = (list: any) => {
    return (
      showDom ? <div className={styles.listWarp}>
        {
          list?.length > 0 ?
            <AntdRefreshList
              height={height}
              initialListSize={pageSize}
              dataSource={list}
              refreshing={refreshing}
              loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div className={styles.cardItem} key={index}>
                  <SwipeActionItem index={index} item={item} dataList={list} {...props} ChangMembers={ChangMembers} />
                </div>
              )}
              onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            /> : (
              <EmptyRefresh
                refreshing={refreshing}
                onRefresh={handleRefresh} />
            )
        }
      </div> :
        <EmptyLoading />
    );

  };

  const statusFn = () => {
    if (searchStatus) {
      if (dataSource?.length <= 0) {
        return <Empty text={'没有找到' + searchValue + '相关记录'} />
      } else if (!dataSource) {
        return <Empty isError={isError} text={'无网络连接'} reloadText="重新加载" reload={() => handleSearch({ keyWord: '' })} />
      } else {
        return actionList(dataSource)
      }
    } else {
      if (!dataSource) {
        return <Empty isError={isError} text={'无网络连接'} reloadText="重新加载" reload={() => handleSearch({ keyWord: '' })} />
      } else {
        return actionList(dataSource)
      }
    }
  }

  // 清除搜索中的数据
  const initDataFn = () => {
    handleSearch({ keyWord: '' })
  }


  return (
    <div className={styles.memberWrap}>
      <div className={styles.search}>
        <SearchBar
          placeholder="开户姓名/手机号/证件号"
          maxLength={64}
          value={searchValue}
          onCancel={() => {
            setSearchStatus(false);
            setSearchValue('');
            initDataFn()
          }}
          onClear={() => {
            initDataFn()
          }}
          onChange={(val) => {
            handleSearchFn(val);
          }}
        />
      </div>
      {
        statusFn()
      }
      <div className={styles.footer}>
        <Button type="primary" className={styles.addButton} onClick={onAdd}>+添加人员</Button>
      </div>
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default Member;